<script setup>
import {
  roomMessageService,
  roomHeadFileServices,
  getRoomImagesService,
  getRoomMessageImgService,
  updataRoomDataService2,
  insertRoomImagesService,
  insertRoomMessageImgService,
  delRoomData2Service,
  delRoomImagesService,
  delRoomMessageImgService,
} from '@/api/room'
import { ref, onMounted, computed } from 'vue'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { useRoomStore } from '@/stores'
import axios from 'axios'

const roomStore = useRoomStore()
const channelList = ref([]) //定义房间列表
const loading = ref(false) //loading
const total = ref(0) // 总条数
const id = ref(0) //获取房间room_id
const isclick = ref(false)
const isclick2 = ref(false)
//获取房间列表信息
const getChannelList = async () => {
  loading.value = true
  const res = await roomMessageService()
  roomStore.setRoomMessage(res.data.data)
  channelList.value = roomStore.roomMessage
  total.value = res.data.data.length
  loading.value = false
}
// 一进页面就加载
onMounted(() => {
  getChannelList()
})

const roomMessage = ref({
  room_name: '',
  room_type: '',
  price: null,
  description: '',
  amenities: '',
  status: '',
})

const rules = {
  price: [
    {
      required: true,
      message: '价格不能为空',
      trigger: 'blur',
    },
    {
      type: 'number',
      message: '价格必须是数字',
      trigger: ['blur', 'change'],
      transform(value) {
        return Number(value)
      },
    },
  ],
  description: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
  amenities: [{ required: true, message: '便利设施不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '房间状态不能为空', trigger: 'blur' }],
}
//下拉菜单的选项列表
const selectedId = ref(null)
const roomStatus = ref([
  { id: 'available', label: '空房' },
  { id: 'booked', label: '已预定' },
  { id: 'under_maintenance', label: '正在维修' },
])
// 获取选中房间的名称
const getRoomStatus = (roomId) => {
  const room = roomStatus.value.find((r) => r.id === roomId)
  roomMessage.value.status = room.id
  console.log(
    'room_status===',
    room.id,
    ' roomMessage.value.room_status===',
    roomMessage.value.room_status,
  )
}
//控制抽屉盒子是否显示
const visibleDrawer = ref(false)

//上传图片
const imgUrl = ref([])
const fileList = ref([]) // 文件列表
const imgUrl2 = ref([])
const fileList2 = ref([]) // 文件列表
let formData = new FormData()
let formData2 = new FormData()

const onUploadFile = (uploadFile) => {
  fileList.value.push(uploadFile.raw) // 将文件存入 fileList
  //创建一个新的数组保存所有图片预览链接
  imgUrl.value = fileList.value.map((file) => URL.createObjectURL(file)) // 生成预览 URL
}
const onUploadFile2 = (uploadFile) => {
  fileList2.value.push(uploadFile.raw)
  //创建一个新的数组保存所有图片预览链接
  imgUrl2.value = fileList2.value.map((file) => URL.createObjectURL(file))
}

const confirm = async () => {
  if (roomMessage.value.status !== selectedId.value) {
    getRoomStatus(selectedId.value)
  }
  console.log(roomMessage.value)
  const updatedRoomMessage = { ...roomMessage.value, room_id: id.value }
  await updataRoomDataService2(updatedRoomMessage) //更新rooms表信息

  if (fileList.value.length !== 0) {
    formData = new FormData()
    //将所有文件添加到 FormData 中，字段名 'file' 对应后端的接收字段
    fileList.value.forEach(async (file) => {
      formData.append('file', file) // 这里是将所有文件都添加到 FormData
    })
    const res = await roomHeadFileServices(formData) //获取到URL
    console.log(res.data.fileUrls)
    res.data.fileUrls.forEach(async (image_url) => {
      await insertRoomImagesService({ room_id: id.value, image_url }) //上传URL
    })
    imgUrl.value = []
    fileList.value = []
  }
  if (fileList2.value.length !== 0) {
    formData2 = new FormData()
    fileList2.value.forEach(async (file) => {
      formData2.append('file', file) // 这里是将所有文件都添加到 FormData
    })
    const res2 = await roomHeadFileServices(formData2)
    console.log(res2.data.fileUrls) //Url是对象，添加到数据库要一个个添加

    res2.data.fileUrls.forEach(async (image_url) => {
      await insertRoomMessageImgService({ room_id: id.value, image_url }) //上传URL
    })
    fileList2.value = []
    imgUrl2.value = []
  }

  ElMessage({ type: 'success', message: '修改成功' })
  getChannelList()
  visibleDrawer.value = false
}

// 将网络图片地址转换为File对象
async function fetchImageAsFile(imageUrl, filename) {
  try {
    const response = await axios.get(imageUrl, { responseType: 'arraybuffer' })
    const imageData = response.data
    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] })
    // 第三步：创建一个新的File对象
    // 创建File对象，文件名和MIME类型可以通过blob的类型推断出来
    const file = new File([blob], filename, { type: blob.type })

    return file
  } catch (error) {
    console.error('Error:', error)
    return null
  }
}

//编辑房间列表信息
const onEditChannel = async (row) => {
  imgUrl.value = []
  imgUrl2.value = []
  visibleDrawer.value = true
  id.value = row.room_id
  roomMessage.value = {
    room_name: row.room_name,
    room_type: row.room_type,
    price: row.price,
    description: row.description,
    amenities: row.amenities,
    status: row.status,
  }
  selectedId.value = row.status
  const res = await getRoomImagesService(row.room_id)
  const res2 = await getRoomMessageImgService(row.room_id)
  console.log(res.data.data, res2.data.data)

  if (res.data.data.length !== 0) {
    isclick.value = true
    const filesArray = [] // 用于存储所有的 file 对象
    // 将所有的异步操作都放入一个数组
    const promises = res.data.data.map((url) => {
      const filename = url.image_url.match(/[^/]+$/)[0] // 使用正则表达式提取文件名
      console.log(filename)

      // 返回一个 Promise，等待文件加载完成
      return fetchImageAsFile(url.image_url, filename)
        .then((file) => {
          if (file) {
            console.log('File object:', file)
            filesArray.push(file) // 直接存储 file 对象
          }
        })
        .catch((error) => console.error('Error in fetching image:', error))
    })

    // 等待所有 Promise 都执行完毕
    Promise.all(promises)
      .then(() => {
        // 所有异步操作完成后，filesArray 就包含了所有的 file 对象
        console.log('All files:', filesArray)

        // 你可以在这里使用文件对象，例如生成 object URL
        filesArray.forEach((file) => {
          imgUrl.value.push(URL.createObjectURL(file))
        })
      })
      .catch((error) => {
        console.error('Error in one of the promises:', error)
      })
  } else isclick.value = false
  if (res2.data.data.length !== 0) {
    isclick2.value = true
    const filesArray = [] // 用于存储所有的 file 对象
    // 将所有的异步操作都放入一个数组
    const promises = res2.data.data.map((url) => {
      const filename = url.image_url.match(/[^/]+$/)[0] // 使用正则表达式提取文件名
      console.log(filename)

      // 返回一个 Promise，等待文件加载完成
      return fetchImageAsFile(url.image_url, filename)
        .then((file) => {
          if (file) {
            console.log('File object:', file)
            filesArray.push(file) // 直接存储 file 对象
          }
        })
        .catch((error) => console.error('Error in fetching image:', error))
    })

    // 等待所有 Promise 都执行完毕
    Promise.all(promises)
      .then(() => {
        // 所有异步操作完成后，filesArray 就包含了所有的 file 对象
        console.log('All files:', filesArray)
        // 你可以在这里使用文件对象，例如生成 object URL
        filesArray.forEach((file) => {
          imgUrl2.value.push(URL.createObjectURL(file))
        })
      })
      .catch((error) => {
        console.error('Error in one of the promises:', error)
      })
  } else isclick2.value = false

  //Promise {<pending>} 是因为 Promise 可能还在执行中，
  // 并且它是一个异步操作的返回值。你看到的 [[PromiseState]]: "fulfilled"
  // 表示该 Promise 已经被解决，并且 [[PromiseResult]] 中包含了 File 对象。
  //方法 1：使用 .then() 来处理异步 Promise
  console.log(imgUrl.value)
}

// 删除房间列表信息
const onDelChannel = async (row) => {
  console.log(row.room_id)
  await ElMessageBox.confirm('你确认删除该该条数据吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
  await delRoomMessageImgService(row.room_id)
  await delRoomImagesService(row.room_id)
  await delRoomData2Service(row.room_id)
  ElMessage({ type: 'success', message: '删除成功' })
  getChannelList()
}

//分页
const currentPage = ref(1) // 当前页
const pagesize = ref(3) // 每页条数
// pagesize每页条数 改变时触发
const onSizeChange = (size) => {
  currentPage.value = 1
  pagesize.value = size
  getChannelList()
}
// 分页数据计算属性
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pagesize.value
  const end = start + pagesize.value
  return channelList.value.slice(start, end)
})

// currentPage 当前页 改变时触发
const onCurrentChange = (page) => {
  currentPage.value = page
  getChannelList()
}
</script>
<template>
  <page-container title="房间管理">
    <div>
      <el-table :data="paginatedData" v-loading="loading" style="width: 100%; margin-top: 20px">
        <el-table-column label="房间ID" align="center" width="100">
          <template #default="{ $index }">
            <!-- 当前页的索引加上偏移量来计算序号 -->
            {{ $index + 1 + (currentPage - 1) * pagesize }}
          </template>
        </el-table-column>
        <el-table-column label="房间名称" prop="room_name" align="center"></el-table-column>
        <el-table-column label="房间类型" prop="room_type" align="center"></el-table-column>
        <!-- 图片列 -->
        <el-table-column label="房间图片" align="center">
          <template #default="{ row }">
            <img
              :src="row.room_img"
              alt="房间图片"
              style="width: 100px; height: 60px; object-fit: cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="price" align="center">
          <template #default="{ row }">
            <span>{{ row.price || '暂无数据' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="description" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.description || '暂无数据' }}</span>
          </template></el-table-column
        >
        <el-table-column label="便利设施" prop="amenities" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.amenities || '暂无数据' }}</span>
          </template></el-table-column
        >
        <el-table-column label="状态" prop="status" align="center">
          <template #default="{ row }">
            <span v-if="row.status === 'available'">空房</span>
            <span v-else-if="row.status === 'booked'">已预定</span>
            <span v-else>正在维修</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <!-- row 就是 channelList 的一项，类似于item； $index 下标 -->
          <template #default="{ row }">
            <el-button
              :icon="Edit"
              circle
              plain
              type="primary"
              @click="onEditChannel(row)"
            ></el-button>
            <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="onDelChannel(row)"
            ></el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据"></el-empty>
        </template>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pagesize"
        :page-sizes="[2, 3, 4, 5, 10]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
      <el-drawer v-model="visibleDrawer" title="编辑" direction="rtl" size="50%">
        <div>
          <el-form
            ref="form"
            style="max-width: 600px"
            :model="roomMessage"
            status-icon
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item label="房间名称">
              <el-input
                v-model="roomMessage.room_name"
                style="width: 350px"
                disabled
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="房间类型">
              <el-input
                v-model="roomMessage.room_type"
                style="width: 350px"
                disabled
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input
                v-model.number="roomMessage.price"
                style="width: 350px"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="roomMessage.description" style="width: 350px" />
            </el-form-item>
            <el-form-item label="便利设施" prop="amenities">
              <el-input v-model="roomMessage.amenities" style="width: 350px" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <template #default>
                <el-select v-model="selectedId" style="width: 350px" placeholder="请选择状态">
                  <el-option
                    v-for="item in roomStatus"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-form-item>
            <!-- :multiple="true"  允许选择多个文件 -->
            <el-form-item label="轮播图">
              <template #default>
                <el-upload
                  class="avatar-uploader"
                  :multiple="true"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="onUploadFile"
                  :disabled="isclick"
                >
                  <div v-if="imgUrl" class="image-preview-container">
                    <div v-for="(image, index) in imgUrl" :key="index" class="image-preview">
                      <img :src="image" alt="Image Preview" />
                    </div>
                  </div>
                  <el-icon v-if="imgUrl.length === 0" class="avatar-uploader-icon"
                    ><Plus
                  /></el-icon>
                </el-upload>
              </template>
            </el-form-item>
            <el-form-item label="详情图">
              <template #default>
                <el-upload
                  class="avatar-uploader"
                  :multiple="true"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="onUploadFile2"
                  :disabled="isclick2"
                >
                  <div v-if="imgUrl2" class="image-preview-container">
                    <div v-for="(image, index) in imgUrl2" :key="index" class="image-preview">
                      <img :src="image" alt="Image Preview" />
                    </div>
                  </div>
                  <el-icon v-if="imgUrl2.length === 0" class="avatar-uploader-icon"
                    ><Plus
                  /></el-icon>
                </el-upload>
              </template>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="visibleDrawer = false">取消</el-button>
            <el-button type="primary" @click="confirm"> 提交 </el-button>
          </span>
        </template>
      </el-drawer>
    </div>
  </page-container>
</template>
<style lang="scss" scoped>
.el-table {
  margin-top: 20px;
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 150px;
      height: 130px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-preview img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}
</style>
